<template>
  <div>
    <el-card :class="{'cardInTab':true}" shadow="never" key="card1">

      <el-row :class="['searchBar']" :gutter="20">
        <el-col :span="4">
          <el-cascader
            placeholder="搜索分类"
            clearable
            :props="props"
            :options="prodCates"
            size="medium"
            @change="handleCateSelectionChange"
            filterable></el-cascader>
        </el-col>
        <el-col :span="6">
          <el-radio-group v-model="pageReqParams.banSale" @change="handleBanSaleChange">
            <el-radio-button label="-1">所有商品</el-radio-button>
            <el-radio-button label="0">已上架商品</el-radio-button>
            <el-radio-button label="1">已下架商品</el-radio-button>
          </el-radio-group>
        </el-col>
        <el-col :span="7">
          <el-input placeholder="搜索商品名称"
                    clearable
                    class="input-with-select"
                    @input="handleSearchProductsButtonClick()"
                    v-model="pageReqParams.query">
          </el-input>
        </el-col>
        <el-col :span="7">
          <el-autocomplete
            v-model="pageReqParams.brandQuery"
            clearable
            @input="handleSearchProductsButtonClick()"
            :fetch-suggestions="handleQuerySearchBrand"
            placeholder="搜索品牌" class="input-with-select"
            value-key="name"
            style="width: 300px"
            @select="handleBrandSelect"
          ></el-autocomplete>
        </el-col>
      </el-row>
      <el-row :class="['btnBar']">


        <el-button-group>
          <el-button type="primary" @click="handleAddProductButtonClick()">添加商品</el-button>
          <el-button type="primary" @click="handleBanSaleButtonClick(1)">下架商品</el-button>
          <el-button type="primary" @click="handleBanSaleButtonClick(0)">上架商品</el-button>
          <el-button type="danger" @click="handleDeleteProductButtonClick">删除商品</el-button>
        </el-button-group>
      </el-row>

      <el-table
        :class="['table-border']"
        :row-key="getRowKey"
        :data="pageInfo.list"
        border
        stripe
        fit
        highlight-current-row
        @selection-change="handleSelectionChangeInSpuTable"
      >

        <el-table-column type="selection" width="60">
        </el-table-column>
        <el-table-column label="序号" type="index" width="50"></el-table-column>
        <el-table-column
          prop="code"
          label="SPU编码"
        >
        </el-table-column>
        <el-table-column
          width="300"
          prop="name"
          label="商品名称">
        </el-table-column>
        <el-table-column
          width="150"
          prop="brandName"
          label="品牌"
        >
        </el-table-column>
        <el-table-column
          label="上架/下架"
          width="90"
          align="center"
        >
          <template slot-scope="scope">
            <el-switch
              :active-value="0"
              :inactive-value="1"
              v-model="scope.row.banSale"
              @change="handleSpuStatusChange(scope.row)"
              active-color="#13ce66"
              inactive-color="#ff4949">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column
          label="分类"
          width="200"
        >
          <template slot-scope="scope">
            {{scope.row.cate1Name}} > {{scope.row.cate2Name}} > {{scope.row.cate3Name}}
          </template>
        </el-table-column>
        <el-table-column
          width="200"
          prop="brief"
          label="简介">
        </el-table-column>
        <el-table-column label="操作" width="300"
        >
          <template slot-scope="scope">
            <el-button type="primary" @click="handleSpuDetailsButtonClick(scope.row)">商品详请</el-button>
            <el-button type="danger" @click="handleDeleteOneSpuButtonClick(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handlePageSizeChange"
        @current-change="handleCurrentPageNumberChange"
        :current-page="pageInfo.pageNum"
        :page-sizes="pageSizes"
        :page-size="pageInfo.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pageInfo.total">
      </el-pagination>
    </el-card>
  </div>
</template>

<script>
  import {mapState, mapMutations} from 'vuex';
  import {prodTabNameList} from '../../config/variable'

  export default {
    name: "ProdList",

    data() {
      return {

        prodTabNameList:prodTabNameList,

        //级联选择器的属性映射
        props: {
          value: 'id',
          label: 'name',
          leaf: 'isLeaf',
          expandTrigger: 'hover'
        },

        // 分页请求时要携带的参数
        pageReqParams: {
          query: '',
          pageNum: 1,
          pageSize: 20,
          brandQuery: '',
          cateId: null,
          banSale: -1
        },
        // 分页信息
        pageInfo: {
          pageNum: 0,
          pageSize: 0,
          total: 0,
          totalPage: 0,
          list: []
        },
        // 分页的大小常量列表
        pageSizes: [5, 10, 20, 30],
        // 记录表格选中行,用于批量操作
        selectionInSpuTable: []
      }
    },


    computed: {

      ...mapState({
        ossServer:state=>state.prod.ossServer,
        imageServer: state=>state.prod.imageServer,
        prodCates: state=>state.prod.prodCates,
        prodCurrentSpu: state=>state.prod.prodCurrentSpu,
        prodCurrentSpuImages:state=>state.prod.prodCurrentSpuImages
      })
    },

    created() {
      this.getProductPageFunction();
    },

    methods: {
      ...mapMutations(['setOssServer', 'setImageServer','setProdCurrentSpu','setProdCurrentSpuImages','setProdActiveTabName']),

      handleBrandSelect(brand){
        this.pageReqParams.brandQuery = brand.name;
      },
      handleQuerySearchBrand(query,cb){
        this.api.__api__BrandsByQuery(query)
          .then(data=>{
            cb(data.data);
          })
      },


      getRowKey(row) {
        return row.id;
      },

      //处理SPU表格的选中行改变
      handleSelectionChangeInSpuTable(selection) {
        this.selectionInSpuTable = selection;
      },

      //处理上架下架
      handleBanSaleButtonClick(banSale) {
        if (this.selectionInSpuTable.length == 0) {
          this.$message.info("请选中一个或多个spu");
          return;
        }
        const spuIdList = [];
        for (let spu of this.selectionInSpuTable) {
          spuIdList.push(spu.id);
        }
        this.api.__api__ProductSpusBanSaleUpdate(spuIdList, banSale)
          .then(data => {
            this.getProductPageFunction();
          })
          .catch(error => this.$message.error(error));
      },

      //处理删除一个SPU
      async handleDeleteOneSpuButtonClick(row) {
        const result = await this.$confirm("您确定要删除编码为[" + row.code + "]的SPU吗？", "提示",).catch(error => null);
        if (result === 'confirm') {
          this.api.__api__ProductSpuDelete(row.id)
            .then(data => {
              this.getProductPageFunction();
              this.$message.success(data.message);
            })
            .catch(error => console.error(error))
        }

      },

      //处理批量删除SPU按钮
      async handleDeleteProductButtonClick() {
        if (this.selectionInSpuTable.length == 0) {
          this.$message.info("请选中一个或多个spu");
          return;
        }
        const result = await this.$confirm("您确定要删除选中的SPU吗？", "提示",).catch(error => null);
        if (result !== 'confirm') {
          return;
        }
        const spuIdList = [];
        for (let spu of this.selectionInSpuTable) {
          spuIdList.push(spu.id);
        }

        this.api.__api__ProductSpusDelete(spuIdList)
          .then(data => {
            this.getProductPageFunction();
          })
          .catch(error => this.$message.error(error));
      },

      //处理上架下架触发搜索请求数据
      handleBanSaleChange(label) {
        this.getProductPageFunction();
      },

      //处理上架下架一个SPU
      handleSpuStatusChange(spu) {
        this.api.__api__ProductSpuBanSaleUpdate(spu.id, spu.banSale)
          .then(data => {
            this.$message.success(data.message);
          })
          .catch(error => {
            this.$message.error(spu.banSale == 0 ? "上架操作失败" : "下架操作失败");
            spu.banSale = Math.abs(spu.banSale - 1);
          });
      },

      //处理选择分类后触发搜索
      handleCateSelectionChange(val) {
        this.pageReqParams.cateId = val[val.length - 1];
        this.getProductPageFunction();
      },



      //处理SPU商品详情按钮
      handleSpuDetailsButtonClick(row) {
        this.setProdCurrentSpu(row);

        var p1 = undefined;
        var p2 = undefined;
        var p3 = undefined;
        var p4 = undefined;
        if (!row.attrs) {
          p1 = this.api.__api__CategoriesAttrs(row.cate3Id);
        }

        if (!row.specs) {
          p2 = this.api.__api__CategoriesSpecs(row.cate3Id);
        }



        if (!row['images']) {
          p3 = this.api.__api__ProductSpuImages(row.id);
        }


        //因为以后对skus的修改都将需要skus对应的表格刷新，所以才将刷新动作放在ProdDetails的mounted方法中去
        row.skus = [];

        Promise.all([p1, p2, p3]).then(values => {
          if (p1 !== undefined) {
            row.attrs = values[0].data;
          }
          if (p2 !== undefined) {
            row.specs = values[1].data;
          }

          if (p3 !== undefined) {
            row.images = values[2].data;
            this.setProdCurrentSpuImages( values[2].data );
          }
          console.log("开始设置 details显示");
          this.setProdActiveTabName(prodTabNameList.prodDetails);
        }).catch(errors => {
          console.error(errors)
        })
      },

      //处理搜索触发
      handleSearchProductsButtonClick() {
        this.getProductPageFunction();
      },

      //打开添加面板
      handleAddProductButtonClick() {
        this.setProdActiveTabName(prodTabNameList.prodSpuAdd);
      },

      //处理分页大小败变
      handlePageSizeChange(size) {
        this.pageInfo.pageSize = size;
        this.pageReqParams.pageSize = size;
        this.getProductPageFunction();
      },

      //处理页选择
      handleCurrentPageNumberChange(pageNum) {
        this.pageReqParams.pageNum = pageNum;
        this.getProductPageFunction();
      },

      //获取分页数据
      getProductPageFunction() {
        this.api.__api__ProductSpusPage(this.pageReqParams)
          .then(data => {
            this.pageInfo = data.data;
          })
          .catch(error => {
            this.pageInfo = {
              pageNum: 0,
              pageSize: 0,
              total: 0,
              totalPage: 0,
              list: []
            };
          })
      }
    }
  }
</script>

<style scoped>

</style>
